<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2015/12/7
 * Time: 14:38
 */
//header("Content-type: text/html; charset=utf-8");
class Smtexcel extends MY_Controller{
    function __construct() {
        parent::__construct();
        //加载模型
       /* $roleAry = array('admin','Shaozhuqiang','jay','judy','lyb','prezwang','david','karina','anna','zlj','AlexTM');
        if(!in_array($this->users['account'],$roleAry)){
            js_goto('','你没有权限！','');
           // redirect(blang_url('orders/order'));

            return;
        }*/
        $this->load->model('Smt_model');
        $this->load->model('Brand_model');
    }
    public function index(){

    }
    //上传文件并生成预�?
    public function upload($type=''){
        set_time_limit(0);
        $action=$_POST['action'];
        if($action=="submit"){
            $uploaddir = './resource/uploadfiles/file/excels/';//上传的文件保存在当前目录
            $uploadfile = $uploaddir . basename($_FILES['fileField']['name']);//取得PHP上传文件�?
            //开始移动PHP上传的临时文件到当前目录�?
            if (move_uploaded_file($_FILES['fileField']['tmp_name'], $uploadfile)) {
                $excelData=$this->duquexcel($_FILES['fileField']['name']);
                if($type=='list') {
                    $data['count'] = $excelData;
                    $data['smtarray'] = $excelData[0];
                    //数字标识 用于判断是上传文件还是提交文件数据入�?0 上传 1 入库
                    $data['numto'] = 1;
                    //用于存储文件名称 用来上传以后 选择性是否存储数据入�?
                    $data['filesname'] = $_FILES['fileField']['name'];
                    //方法标识�?表示表单数据提交到哪个方�?
                    $data['fct'] = 'addsmt';
                    //数据提示信息
                    $data['tishi'] = '';
                    //查询所有单�?进行匹配
                    $oerderidlist = $this->Smt_model->seachid();
                    foreach ($oerderidlist as $ddlist) {
                        $arrlistid[] = $ddlist['parent_order_id'];
                    }
                    $data['oerderidlist'] = empty($arrlistid) ? array() : $arrlistid;
                    $this->load->view('defaults/smt_excel', $data);
                }else{
                    if(count($excelData[0]) == 3) {
                        for ($i = 1; $i < count($excelData); $i++) {
                            $id = $excelData[$i][0];
                            $time = strtotime($excelData[$i][1]);
                            $wbstarttime = $time + 15 * 24 * 3600;
                            $wbendtime = $wbstarttime + 365 * 24 * 3600;
                            $arr = array(
                                'warranty_start_time' => $wbstarttime,
                                'warranty_end_time' => $wbendtime,
                            );
                            $this->Smt_model->updatewbtime($id, $arr);
                        }
                    }else{
                        js_goto('','请上传合格的EXCEL','1');
                        return false;
                    }
                    $this->smtlist('');

                }
            } else {
                js_goto('','上传失败！！','1');
            }
        }

    }
    //显示速卖通数据列�?
    public function smtlist($page=''){
        $gp=gp();
        //数字标识 用于判断是上传文件还是提交文件数据入�?0 上传 1 入库
        $data['numto']=0;
        //用于存储文件名称 用来上传以后 选择性是否存储数据入�?
        $data['filesname']='';
        //方法标识�?表示表单数据提交到哪个方�?
        $data['fct']='upload';
        $data['tishi']=lang('smtqscxlxs');
        $page?$page=$page:$page=1;
        $this->load->library('pagination');

        $config['base_url'] = blang_url('orders/Smtexcel/smtlist');
        $config['total_rows'] = $this->Smt_model->zongsu();
        $config['uri_segment'] = config_item('enable_lang')?5:4;
        $config['per_page'] = 20;

        $this->pagination->initialize($config);

        $data['pageshow']= $this->pagination->create_links();
        $data['query']=$this->Smt_model->select(trim($gp['id']),trim($gp['name']),$gp['country'],'',$config['per_page'],($page-1)*$config['per_page']);
        $data['gj']=$this->Smt_model->selectCustom('mt_repair_site');
        if($gp['id']){
            $signUrl=$this->GetAliExpressOrder($gp['id']);
            $ep=$signUrl[0];
            $eplist['warrantyStatus']=$ep['warrantyStatus'];
            $eplist['orderId']=$ep['orderId'];
            $eplist['name']=$ep['name'];
            $eplist['streetAddress']=$ep['streetAddress'];
            $eplist['city']=$ep['city'];
            $eplist['province']=$ep['province'];
            $eplist['country']=$ep['country'];
            $eplist['telephone']=$ep['telephone'];
            $eplist['serviceStartTime']=$ep['serviceStartTime'];
            $eplist['productCount']=$ep['productCount'];
            $eplist['productName']=$ep['productName'];
            $eplist['description']=$ep['description'];
            $eplist['attachments']=$ep['attachments'];
            $data['eplist']=$eplist;
        }
        $this->load->view('defaults/smt_list',$data);
    }
    /**
     * 显示无法识别数据
     */
    public function smtzhaobudao($keyword=''){
       // $this->deletesc($keyword);
        $data['tishi']=$keyword;
        $data['btlist']=$this->Smt_model->select('','','',1,'','');
        $data['btlist2']=$this->Smt_model->select('','','',3,'','');
        $shit=$this->smtdatamat2($data['btlist2'],'');
        $brandlistno=array();
        if($shit) {
            $data['bdname'] = array_keys($shit['brandstrno']);
            foreach($shit['brandstrno'] as $key=>$val) {
                for($i=0;$i<count($val);$i++) {
                        $brandlistno[$val[$i]]=$key;
                }
            }
        }
        $data['btlistno']=$brandlistno;
        $this->load->view('defaults/smt_listno',$data);
    }

    /**
     * 显示数买通详细数据统�?
     * @param $id
     */
    public function smtxxfx($page='',$model=''){
        $gp=gp();
        if($model){
            $gp['model']=rawurldecode($model);
        }
        /*$page?$page=$page:$page=1;
        $this->load->library('pagination');

        $config['base_url'] = blang_url('orders/Smtexcel/smtxxfx');
        $config['total_rows'] = $this->Smt_model->countpcm($gp['brand'],$gp['model'],$gp['country']);
        $config['uri_segment'] = config_item('enable_lang')?5:4;
        $config['per_page'] = 20;

        $this->pagination->initialize($config);

        $data['pageshow']= $this->pagination->create_links();*/
        $data['query']=$this->Smt_model->smtxxlit($gp['brand'],$gp['model'],$gp['country']);
        $data['gj']=$this->Smt_model->selectCustom('mt_repair_site');
        $this->load->view('defaults/smt_xx_list',$data);
    }

    /**
     * 显示所有二手机
     */
    public function usedlist(){
        $gp=gp();
        $data['usedlist']=$this->Smt_model->usedlist(trim($gp['brand']),trim($gp['model']),trim($gp['country']));
        $data['gj']=$this->Smt_model->selectCustom('mt_repair_site');
        $this->load->view('defaults/used_list',$data);
    }
    /**
     * 查询单个无法匹配信息
     */
    public function postbrandmodel($id,$brand=''){
        $data['query']=$this->Smt_model->selectnosmt($id);
        if($brand) {
            $data['brand'] = $brand;
            $data['models']=$this->Smt_model->brandlist($brand);
        }
        $this->load->view('defaults/model_post',$data);
    }
    /**
     * 添加品牌型号信息 这里的任何一步操作都将影响所有计算出来的数据 请慎重修�?
     */
    public function addbrandmodel($id){
        $gp=gp();
        $gp['brand']=trim($gp['brand']);
        $gp['model']=trim($gp['model']);
        $addtrue = $this->Smt_model->updateidname($id, trim($gp['names']));
        //如果修改了商品名 则重新拿商品名进行匹�?
        if ($addtrue) {
            //重新查询订单全部信息 不能只取名字 因为要分日期和国家做不同记录
            $datanames = $this->Smt_model->seachxiangqing($id);
            $bbblist = '';
        }
        if($gp['brand']!="" && $gp['model']!="") {
            $ssslist=$this->Smt_model->jqbrand($gp['brand'],$gp['model']);
            if($ssslist){
                js_goto('','品牌型号已经存在，请不要重复添加?','1');
                return false;
            }else {
                $this->Smt_model->addstm(array('brand' => $gp['brand'], 'model' => $gp['model']));
                $tishi="<span style='color:#4a9bdf;'>温馨提示</span>：成功添加品牌：<span style='color:red;'>".$gp['brand']."</span>型号�?span style='color:red;'>".$gp['model']."</span>";
            }
            //如果增加了品牌型�?则重新拿品牌型号匹配
            $datanames=$this->Smt_model->select();
            $bmlist['brand']=array(array('brand'=>$gp['brand']));
            $bmlist['model']=array(array('model'=>$gp['model']));
            $bbblist=$bmlist;
        }
        if($datanames) {
            $s66666 = $this->smtdatamat2($datanames, $bbblist);
            $datas = $s66666['datas'];
            $numsss = 0;
            if ($datas) {
                foreach ($datas as $row) {
                    $numsss += $row['number'];
                    $datafeiqi = array($row);
                    $this->Smt_model->updateid($row['parent_order_id']);
                    $p1time = $this->Smt_model->maxtime666('smt_pcm');
                    if ($row['time'] < $p1time['time']) {
                        $this->smtfengxi($datafeiqi, 'smt_pcm');
                        $this->smtfengxi($datafeiqi, 'smt_pcm2');
                        //对二手机进行新增量减半操�?
                        $numarray = array(
                            'number' => 'number-' . $row['number'],
                        );
                        $this->Smt_model->updateset("smtused", $numarray, array('brand' => $row['brand'], 'model' => $row['model'], 'country' => $row['country']));
                    } else {
                        $this->smtfengxi($datafeiqi, 'smt_pcm2');
                    }
                }
                $tishi = $tishi . "新增数据�?" . $numsss;
                //对前表进行数据补零同�?
                $pcm2 = $this->Smt_model->smtxxclist();
                $mitime = $this->Smt_model->mintimepcm('smt_pcm');
                if ($pcm2) {
                    foreach ($pcm2 as $row) {
                        $data = array(
                            'brand' => $row['brand'],
                            'model' => $row['model'],
                            'number' => 0,
                            'country' => $row['country'],
                            'time' => $mitime['time'],
                        );
                        $this->Smt_model->addsmtpcm('smt_pcm', $data);
                    }
                }
                $pcm = $this->Smt_model->smtxxclist2();
                $mitime2 = $this->Smt_model->mintimepcm('smt_pcm2');
                if ($pcm) {
                    foreach ($pcm as $row) {
                        $data = array(
                            'brand' => $row['brand'],
                            'model' => $row['model'],
                            'number' => $row['number'],
                            'country' => $row['country'],
                            'time' => $mitime2['time'],
                        );
                        $this->Smt_model->addsmtpcm('smt_pcm2', $data);
                    }
                }
            }
        }
        $this->smtzhaobudao($tishi);
    }
    /**
     * 提交excel数据入库
     */
    public  function  addsmt(){
        //循环遍历所有数据并添加到数据库
        $filesname=$_POST['filesname'];
        $time=time();
        $excelData=$this->duquexcel($filesname);
        $time2=strtotime($excelData[1][7]);
        if(count($excelData[0]) != 20){
            js_goto('','导入的excel文件格式不正确！！！','1');
            return false;
        }
        for ($l = 1; $l < count($excelData); $l++) {
            //对ext_value列进行分�?分别存入不同字段
            $strs = substr($excelData[$l][18], 18, -2);
            $strs2 = explode(',', $strs);
            $feeRate = explode(':', $strs2[0]);
            $feeRate = substr($feeRate[1], 1, -1);

            $supplier = explode(':', $strs2[1]);
            $supplier = substr($supplier[1], 1, -1);

            $warrantyPriceAmt = explode(':', $strs2[2]);
            $warrantyPriceAmt = (int)substr($warrantyPriceAmt[1], 1, -1) / 100;

            $warrantyPriceCurrency = explode(':', $strs2[3]);
            $warrantyPriceCurrency = substr($warrantyPriceCurrency[1], 1, -1);

            //把excel时间格式转换为年月日格式
            $times1 = intval(($excelData[$l][7] - 25569) * 3600 * 24);
            $pay_order_time = date('Y/m/d H:i:s', $times1);
            if ($excelData[$l][10] != "\N") {
                $times2 = intval(($excelData[$l][10] - 25569) * 3600 * 24);
                $trade_end_time = date('Y/m/d H:i:s', $times2);
            } else {
                $trade_end_time = $excelData[$l][10];
            }
            //担保开始时�?交易时间+15个工作日
            $warranty_start_time = 0;
            //担保结束时间=担保开始时�?365个工作日
            $warranty_end_time = 0;
            $aff = array(
                'parent_order_id' => $excelData[$l][0],
                'snapshot_id' => $excelData[$l][1],
                'pcate_leaf_id' => $excelData[$l][2],
                'item_id' => $excelData[$l][3],
                'unit_price' => $excelData[$l][4],
                'item_unit' => $excelData[$l][5],
                'crt_item_qty' => $excelData[$l][6],
                'pay_order_time' => $excelData[$l][7],
                'buyer_admin_id' => $excelData[$l][8],
                'seller_admin_id' => $excelData[$l][9],
                'trade_end_time' => $excelData[$l][10],
                'register_country_id' => $excelData[$l][11],
                'register_province_name' => $excelData[$l][12],
                'full_name' => $excelData[$l][13],
                'email' => $excelData[$l][14],
                'buyer_country_id' => $excelData[$l][15],
                'buyer_province' => $excelData[$l][16],
                'buyer_city' => $excelData[$l][17],
                'item_name' => $excelData[$l][19],
                'warrantyPriceAmt' => $warrantyPriceAmt,
                'feeRate' => $feeRate,
                'supplier' => $supplier,
                'warrantyPriceCurrency' => $warrantyPriceCurrency,
                'imptime' => $time,
                'warranty_start_time' => $warranty_start_time,
                'warranty_end_time' => $warranty_end_time,
            );
            $aff2[] = array(
                'parent_order_id' => $excelData[$l][0],
                'snapshot_id' => $excelData[$l][1],
                'pcate_leaf_id' => $excelData[$l][2],
                'item_id' => $excelData[$l][3],
                'unit_price' => $excelData[$l][4],
                'item_unit' => $excelData[$l][5],
                'crt_item_qty' => $excelData[$l][6],
                'pay_order_time' => $excelData[$l][7],
                'buyer_admin_id' => $excelData[$l][8],
                'seller_admin_id' => $excelData[$l][9],
                'trade_end_time' => $excelData[$l][10],
                'register_country_id' => $excelData[$l][11],
                'register_province_name' => $excelData[$l][12],
                'full_name' => $excelData[$l][13],
                'email' => $excelData[$l][14],
                'buyer_country_id' => $excelData[$l][15],
                'buyer_province' => $excelData[$l][16],
                'buyer_city' => $excelData[$l][17],
                'item_name' => $excelData[$l][19],
                'warrantyPriceAmt' => $warrantyPriceAmt,
                'feeRate' => $feeRate,
                'supplier' => $supplier,
                'warrantyPriceCurrency' => $warrantyPriceCurrency,
                'imptime' => $time,
                'warranty_start_time' => $warranty_start_time,
                'warranty_end_time' => $warranty_end_time,
            );
            //添加入库 先入库在综合分析数据 不要分析一条入一�?这样会影响程序效�?
            $this->Smt_model->add($aff);
        }
        $datajl=$this->smtdatamat2($aff2);
        //按两周分别统计数据入�?smt_pcm，smt_pcm2
        $chanum=14*24*3600;
        $mintime=$this->Smt_model->mintimepcm('smt_pcm');
        if($mintime['time']==''){
            $this->smtfengxi($datajl['datas'],'smt_pcm');
        }else{
            $timecha=$time2-$mintime['time'];
            if($timecha < $chanum){
                $this->smtfengxi($datajl['datas'],'smt_pcm');
            }
        }
        $mintime2=$this->Smt_model->mintimepcm('smt_pcm2');
        if($mintime2['time']==''){
            if($timecha > $chanum){
                $this->Smt_model->fuzhitable();
                $this->Smt_model->updatetime($time2);
                $this->smtfengxi($datajl['datas'],'smt_pcm2');
            }
        }else{
            $timecha2=$time2-$mintime2['time'];
            if($timecha > $chanum && $timecha2 < $chanum){
                $this->smtfengxi($datajl['datas'],'smt_pcm2');
            }
            if($timecha2 > $chanum){
                $this->Smt_model->qingkong('smt_pcm');
                $this->Smt_model->fuzhitable2();
                $this->Smt_model->updatetime($time2);
                $this->smtfengxi($datajl['datas'],'smt_pcm2');
            }
        }
        //数据补零同步
        $pcm2=$this->Smt_model->smtxxclist();
        if($pcm2) {
            foreach ($pcm2 as $row) {
                $data = array(
                    'brand' => $row['brand'],
                    'model' => $row['model'],
                    'number' => 0,
                    'country' => $row['country'],
                    'time' => $mintime['time'],
                    'addtime'=>$mintime['time'],
                );
                $this->Smt_model->addsmtpcm('smt_pcm', $data);
            }
        }
        $this->Smt_model->updatesmt($datajl['brandno'],$datajl['modelno']);
        $this->smtlist('');
    }

    /**
     * 将excel文件数据转换为数�?
     * @return array
     * @throws PHPExcel_Exception
     * @throws PHPExcel_Reader_Exception
     */
    public function duquexcel($files){
        //导入EXCEL�?
        $this->load->library('excel/PHPExcel');
        $filetype = pathinfo($files, PATHINFO_EXTENSION);//获取后缀
        if( $filetype =='xlsx' ) {
            $objReader = new PHPExcel_Reader_Excel2007();
        } else {
            $objReader = PHPExcel_IOFactory::createReader('Excel5');
         }
       // $objReader = PHPExcel_IOFactory::createReader('excel2007'); //use excel2007 for 2007 format
        $objReader->setReadDataOnly(true);
        $upload_file = './resource/uploadfiles/file/excels/'.basename($files);
        $objPHPExcel = $objReader->load($upload_file);
        $objWorksheet = $objPHPExcel->getActiveSheet();
        $highestRow = $objWorksheet->getHighestRow(); //总行�?
        $highestColumn = $objWorksheet->getHighestColumn();
        $highestColumnIndex = PHPExcel_Cell::columnIndexFromString($highestColumn); //总列�?
        $excelData = array();
        for ($i = 1; $i <= $highestRow; $i++) {
            $partRows = array();
            for ($j = 0; $j < $highestColumnIndex; $j++) {
                $gridVal = $objWorksheet->getCellByColumnAndRow($j, $i)->getValue();
                $partRows[] = $gridVal;
                //$partRows[] = $gridVal;
            }
            $excelData[] = $partRows;
        }
        foreach( $excelData as $k=>$v){
            if( $v[0]=='' ) {
                unset($excelData[$k]);
            }
        }
        return $excelData;
    }

    /**
     * 查看详情
     */
    public function smtxq($id){
        $data['query']=$this->Smt_model->seachxiangqing($id);
        $this->load->view('defaults/smt_inDetail',$data);
    }
    /**
     * 删除数据
     */
    public function deletesc($id){
        $this->Smt_model->deletesc($id);
        $this->smtzhaobudao('');
    }
    public function deletesc2($id){
        $this->Smt_model->deletesc($id);
        $this->smtlist(1);
    }
    /**
     * 删除品牌
     */
    public function deletebrand($id,$page){
        //删除之前先找出所有与之相匹配的数�?然后进行回滚
        $datanames=$this->Smt_model->select();
        $brandlist=$this->Smt_model->idbrandlist($id);
        $bmlist['brand']=array(array('brand'=>$brandlist['brand']));
        $bmlist['model']=array(array('model'=>$brandlist['model']));
        $data=$this->smtdatamat2($datanames,$bmlist);
        //记录被删品牌 （用于之后判断数据库中是否还存在此品牌，如果不存在回滚到状�? 如果存在回滚到状�?�?
        $brand=$brandlist['brand'];
        //记录被删除型�?（用于后面删除统计信息）
        $model=$brandlist['model'];
        //记录匹配数据
        $datas=$data['datas'];
        //删除品牌和对应型�?
        $this->Smt_model->deletebrand($id);
        //能匹配到数据的话进行状态回滚和统计清楚
        if($datas) {
            //重新查询是否还有相同品牌存在 （因为品牌和型号是一对多关系�?
            $brandlist2=$this->Smt_model->brandbrandlist($brand);
            if($brandlist2){
                $status=3;
            }else{
                $status=1;
            }
            $numsss=0;//记录受影响数�?
            foreach ($datas as $row) {
                $numsss+=$row['number'];
                //回滚所有数据到未识别状�?
                $this->Smt_model->updateidstatus($row['parent_order_id'],$status);
            }
            //删除原有统计信息
            $this->Smt_model->deletepcm1($brand,$model);
            $this->Smt_model->deletepcm2($brand,$model);
            $this->Smt_model->deleteused($brand,$model);
        }
        $this->modellist($page,$numsss);
    }

    /**
     * 数码通订单数据综合处�? 已经弃用 防启�?不删�?
     */
    public function intelligence($type=''){
        //获取速卖通所有订单商品描�?
        $itemnames= $this->Smt_model->smtitemname();
        //$itemnames=$this->Smt_model->sctsmtlist(6*24*3600);
        $modelsetdata=$this->smtdatamat2($itemnames,'');
        $modelsetdata=$modelsetdata['datas'];
        if($modelsetdata) {
            $arrcaocao = array();//记录型号是否已经被统计过
            foreach ($modelsetdata as $row) {
                $num = 0;
                $model = $row['model'];
                $brand = $row['brand'];
                if ($this->in_2array($model,$arrcaocao)==false || $this->in_2array($brand,$arrcaocao)==false) {
                    for ($i = 0; $i < count($modelsetdata); $i++) {
                        if (in_array($model, $modelsetdata[$i])) {
                            $num += $modelsetdata[$i]['number'];
                        }
                    }
                        $modelsetnumtime = array(
                            'number' => $num,
                            'time' => $row['addtime'],
                        );
                        $this->Smt_model->updatemodel($modelsetnumtime, array('model' => $model, 'brand' => $row['brand']));
                }
                $arrcaocao[] = array($model,$brand);
            }
        }
        $this->modellist('');
    }

    /**
     * 数买通各品牌销售数据分购买日期以及国家做不同统计记�?核心方法
     * @param $data
     */
    public function smtfengxi($data,$table='')
    {
        $modelsetdata2 = $data;
        $arrcaocao = array();//记录型号是否已经被统计过
        if($modelsetdata2) {
            foreach ($modelsetdata2 as $row) {
                $num = 0;
                $model = $row['model'];
                $brand = $row['brand'];
                $country=$row['country'];
                $feeRate=$row['feeRate'];
                $peidui[0]=$model.'+'.$brand.'+'.$country;
                $sss = array_intersect($arrcaocao,$peidui);
                //对尚未统计过的品牌型号进行数量累�? 并判断数据库中是否已经存�?存在的话后续品牌型号只做数量累加不新�?
                if (!$sss) {
                    //进行计数
                    for ($i = 0; $i < count($modelsetdata2); $i++) {
                        if ($modelsetdata2[$i]['brand']==$brand && $modelsetdata2[$i]['model']==$model && $modelsetdata2[$i]['country']==$country) {
                            $num += $modelsetdata2[$i]['number'];
                        }
                    }
                    //判断是更新数据还是插入新数据（全�?不区分二手机和新机）
                    $bm=$this->Smt_model->smtpcmbm($table,$row['brand'],$row['model'],$row['country']);
                    if($bm){
                        $modelsetnumtime=array(
                            'number' => 'number+'.$num,
                            'addtime'=>$row['addtime'],
                        );
                        $this->Smt_model->updateset($table,$modelsetnumtime,array('brand'=>$row['brand'],'model'=>$row['model'],'country'=>$row['country']));
                    }else {
                        $modelsetnumtime = array(
                            'brand' => $row['brand'],
                            'model' => $row['model'],
                            'number' => $num,
                            'time' => $row['time'],
                            'country' => $row['country'],
                            'addtime' => $row['addtime'],
                        );
                        $this->Smt_model->addsmtpcm($table,$modelsetnumtime);
                    }
                    /**
                     * 记录二手�?
                     */
                    if($feeRate > 0.05 && $feeRate < 0.15){
                        $bm=$this->Smt_model->smtpcmbm("smtused",$row['brand'],$row['model'],$row['country']);
                        if($bm){
                            $modelsetnumtime=array(
                                'number' => 'number+'.$num,
                                'addtime'=>$row['addtime'],
                            );
                            $this->Smt_model->updateset("smtused",$modelsetnumtime,array('brand'=>$row['brand'],'model'=>$row['model'],'country'=>$row['country']));
                        }else {
                            $modelsetnumtime = array(
                                'brand' => $row['brand'],
                                'model' => $row['model'],
                                'number' => $num,
                                'time' => $row['time'],
                                'country' => $row['country'],
                                'addtime' => $row['addtime'],
                            );
                            $this->Smt_model->addsmtpcm("smtused",$modelsetnumtime);
                        }
                    }
                }
                $arrcaocao[] = $model.'+'.$brand.'+'.$country;
                $arrcaocao=array_unique($arrcaocao);
            }
        }
    }

    /**
     * 显示统计信息
     * @param string $page
     * @param string $nums（受影响数据量）
     */
    public function modellist($page='',$nums=''){
        $page?$page=$page:$page=1;
        $brand = $_POST['brand'];
        $model = $_POST['model'];
        $this->load->library('pagination');

        $config['base_url'] = blang_url('orders/Smtexcel/modellist');
        $config['total_rows'] = $this->Smt_model->countRows('mt_model');
        $config['uri_segment'] = config_item('enable_lang')?5:4;
        $config['per_page'] = 20;

        $this->pagination->initialize($config);
        $data['page']=$page;
        if($nums) {
            $data['nums'] = lang('smtsccgbhgsjl').$nums."  <a style='color: blue' href='".blang_url('orders/Smtexcel/smtzhaobudao')."'>".lang('smtckxq')."</a>";
        }
        $data['pageshow']= $this->pagination->create_links();
        $data['modellist']=$this->Smt_model->brandlist($brand,$model,'',$config['per_page'],($page-1)*$config['per_page']);
        $this->load->view('defaults/model_list',$data);
    }
    /**
     * 数买通数据匹�?算法2 精确度高 效率�?核心方法
     * @param $data
     * @brandlist $brandlist //单型号匹�?
     * @return array
     */
    public function smtdatamat2($data='',$brandmodellist='')
    {
        //品牌数据
        if($brandmodellist) {
            $brandlsit=$brandmodellist['brand'];
        }else{
            $brandlsit = $this->Smt_model->brandlist('', '', 'brand');
        }
        foreach($brandlsit as $bl){
            $bbbb[]=explode(' ',strtolower($bl['brand']));//对品牌进行打�?防止多个单词空格隔开写法
            $brandzhongji[] = strtolower($bl['brand']);//记录完整品牌
        }
        //循环所有订单商品描�?
        //$data=array(array('item_name'=>'Original Xiaomi Redmi Note 3 Prime 32GB ROM Metal Body Fingerprint ID Mobile Phone Helio X10 Octa Core 5.5" 1920X1080 3GB RAM'));
        if ($data) {
            foreach ($data as $row) {
                $cccc=array();//进行型号详细匹配记录 区别各种SB写法
                $modelzhongji=array();//进行型号精确匹配记录（在详细匹配之后才能使用�?
                $ip7s=array();//对匹配完成的型号进行重新组合 用于精确匹配
                $itname = strtolower($row['item_name']);
                $itnamearr = explode(' ', $itname);//考虑到品牌名字或许类�?
                $num = $row['crt_item_qty'];
                $times = $row['pay_order_time'];
                $addtime=$row['imptime'];
                $buyer_country_id=$row['buyer_country_id'];
                $feeRate=$row['feeRate'];
                //匹配品牌
                $brandname=array();
                foreach ($bbbb as $key => $val) {
                    $brandjj = array_intersect($val, $itnamearr);//取品牌交�?
                    if ($brandjj) {
                        $brandname[] = implode(' ',$brandjj);//对能匹配上的品牌进行重组
                    }
                }
                $brandjq=array_intersect($brandzhongji,$brandname);//是否能精确匹配到
                //进行正常化排�?
                $jqbdname=array();
                foreach($brandjq as $key=>$val){
                    $jqbdname[]=$val;
                }
                //对能精确匹配上的品牌进行操作
                if($jqbdname) {
                    $brandname=$jqbdname[0];
                    //匹配型号
                    if($brandmodellist) {
                        $modellsit=$brandmodellist['model'];
                    }else{
                        $modellsit = $this->Smt_model->brandlist($brandname);
                    }
                    foreach ($modellsit as $ml) {
                        $cccc[] = explode(' ', strtolower($ml['model']));//将型号打散记�?
                        $modelzhongji[] = strtolower($ml['model']);//记录完整型号
                    }
                    $modelname = array();//对详细匹配出来的型号名称进行记录
                    foreach ($cccc as $key => $val) {
                        $shitxsss = array_intersect($val, $itnamearr);//取型号交�?
                        if ($shitxsss) {
                            $modelname[] = $shitxsss;
                        }
                    }
                    $maxmodellen = '';
                    //对取出的型号交集进行从新完整组合
                    for ($i = 0; $i < count($modelname); $i++) {
                        $ip7s[] = implode(' ', $modelname[$i]);
                    }
                    //判断是否能精确匹配到
                    $jingque = array_intersect($modelzhongji, $ip7s);
                    if ($jingque) {
                        //对精确型号进行正常下标排�?
                        $jqname=array();
                        foreach($jingque as $key=>$val){
                            $jqname[]=$val;
                        }
                        //对能匹配到的所有型号进行取长判断，排除类似型号 防止SB写法 列如 dooge x5 doogg x5 pro
                        // 两个型号写到一�?或者干�?dooge x5 dooge x6 写到一�?说什么升级版
                        for ($i = 0; $i < count($jqname); $i++) {
                            $j = $i + 1;
                            if ($j > count($jqname) - 1) {
                                $j = count($jqname) - 1;
                            }
                            if (strlen($jqname[$j]) > strlen($jqname[$i])) {
                                $maxmodellen = $jqname[$j];
                            } else {
                                $maxmodellen = $jqname[$i];
                            }
                            $jqname[$j] = $maxmodellen;
                        }
                        //echo $maxmodellen;
                        //对匹配到的信息进行记�?
                        $modelsetdata[] = array(
                            'parent_order_id'=>$row['parent_order_id'],
                            'brand' => $brandname,
                            'model' => $maxmodellen,
                            'number' => $num,
                            'time' => strtotime($times),
                            'addtime'=>$addtime,
                            'country' => $buyer_country_id,
                            'feeRate'=>$feeRate,
                        );
                    }else{
                        //对匹配不到的型号进行记录
                        $modelno[]=$row['parent_order_id'];
                        $brandstrno[$brandname][]=$row['parent_order_id'];
                    }
                }else {
                    //对匹配不到的品牌进行记录
                    $brandno[] = $row['parent_order_id'];
                }
            }
            return array('datas'=>$modelsetdata,
                'brandno'=>$brandno,
                'modelno'=>$modelno,
                'brandstrno'=>$brandstrno,
            );
        }
    }

    /**
     * 生成折线图表数据
     */
    public function LineChartUpdate(){
        $timelinejson=array();//记录时间轴
        $timelinebl=array();//补零时间轴
        $iconJson=array();//折线数据
        //记录时间轴
        $aliExpressTimeline=$this->Smt_model->AliExpressTimeline();
        foreach($aliExpressTimeline as $row){
            $timelinejson[]=$row['times'];
            $timelinebl[]=strtotime($row['times']);
        }
        //各国家的日销售量
        $iconJson['es']=$this->linedata($timelinebl,'es');
        $iconJson['ru']=$this->linedata($timelinebl,'ru');
        $iconJson['de']=$this->linedata($timelinebl,'de');
        $iconJson['us']=$this->linedata($timelinebl,'us');
        $iconJson['uk']=$this->linedata($timelinebl,'uk');
        $iconJson['times']=$timelinejson;
        file_put_contents('./resource/uploadfiles/file/json/aliexpress.json',json_encode($iconJson));
    }
    /**
     * 获取国家日销售量
     * @param $timeline
     * @param $state
     * @return array
     */
    public function linedata($timeline,$state){
        $aliExpressSalesEs=$this->Smt_model->CountAliExpressSales($state);
        if($aliExpressSalesEs) {
            foreach ($aliExpressSalesEs as $row) {
                $iconbl[$state][strtotime($row['times'])] = $row['Sales'];
            }
            //数据补零
            foreach (array_diff($timeline, array_keys($iconbl[$state])) as $key => $val) {
                $iconbl[$state][$val] = 0;
            }
            ksort($iconbl[$state]);
            foreach($iconbl[$state] as $key=>$val){
                $iconJson[]=$val;
            }
            return $iconJson;
        }else{
            return array();
        }
    }

    /**
     * 获取保修服务订单
     * @param int $page
     * @param string $keyword
     */
    public function GetAliExpressWarrantyList(){
        $gp=gp();
        //条件判断
        $gp['page']?$gp['page']=$gp['page']:$gp['page']=1;
        $str='?name='.$gp['name'].'&country='.$gp['country'].'&ctstatus1='.$gp['ctstatus1'];
        //分页查询
        $this->load->library('pagination');
        $config['page_query_string'] = TRUE;
        $config['base_url'] = blang_url('orders/Smtexcel/GetAliExpressWarrantyList'.$str);
        $config['total_rows'] = $this->Smt_model->CountAliExpressWarranty(trim($gp['name']),$gp['country'],$gp['ctstatus1']);
        $config['uri_segment'] = config_item('enable_lang')?5:4;
        $config['per_page'] = 20;
        $this->pagination->initialize($config);
        $data['pageshow']= $this->pagination->create_links();
        $AeList=$this->Smt_model->GetAliExpressWarrantyList(trim($gp['name']),$gp['country'],$gp['ctstatus1'],$config['per_page'],($gp['page']-1)*$config['per_page']);
        //重构数组 生成颜色
        foreach($AeList as &$row){
            switch($row['ctstatus']){
                case '0':
                    $color='';
                    break;
                case '1':
                    $color='#ff9a00';
                    break;
                case '2':
                    $color='#009900';
                    break;
                case '3':
                    $color='#0000ff';
                    break;
                case '4':
                    $color='#ff0000';
                    break;
                case '5':
                    $color='#ff33ff';
                    break;
                default:
                    $color='';
            }
            $row['color']=$color;
        }
        unset($row);
        $data['AeList']=$AeList;
        $this->load->view('defaults/WarrantyList',$data);
    }
    public function aliExpressapi($orderid='',$type=''){
        if($orderid) {
            if($type==2){
                $queryWarrantiesByOrderId = new queryWarrantiesByOrderId();
                $deliveryData = $queryWarrantiesByOrderId->getorder($orderid);
                $deliveryData = (json_decode($deliveryData, true));

                gsh_output($deliveryData);
            }else {
                $queryWarrantiesByOrderId = new queryWarrantiesByOrderId();
                $deliveryData = $queryWarrantiesByOrderId->getorder($orderid);
                $deliveryData = (json_decode($deliveryData, true));
                $cg['streetAddress'] = $deliveryData['dataList'][0]['streetAddress'];
                $cg['city'] = $deliveryData['dataList'][0]['city'];
                $cg['name'] = $deliveryData['dataList'][0]['name'];
                $cg['province'] = $deliveryData['dataList'][0]['province'];
                $cg['serviceStartTime'] = $deliveryData['dataList'][0]['serviceStartTime'];
                $cg['orderId'] = $deliveryData['dataList'][0]['orderId'];
                $cg['telephone'] = $deliveryData['dataList'][0]['telephone'];
                $cg['country'] = $deliveryData['dataList'][0]['country'];
                $cg['productCount'] = $deliveryData['dataList'][0]['productCount'];
                gsh_output($cg);
            }
        }else{
            echo 'orderid is null';
        }
    }
    /**
     * 获取速卖通订单详情
     * @param $orderid
     */
    public function GetAliExpressOrder($orderid){
        $str='api.queryWarrantiesByOrderId';
        $arr=array(
            'supplierId'=>'pandawill',
            'orderId'=>$orderid
        );
        $url=getAliExpressSign($str,$arr);
        $datalist=UrlGet($url);
        return $datalist['dataList'];
    }
    /**
     * url post
     * @param $url
     * @param $data
     * @return mixed
     */
   public function materialpost($url,$data){
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_BINARYTRANSFER,true);
        curl_setopt($ch, CURLOPT_HEADER, false);
        curl_setopt($ch, CURLOPT_POSTFIELDS,http_build_query($data));
        curl_setopt($ch, CURLOPT_URL, $url);
        $response=curl_exec($ch);
        curl_close($ch);
        $result = json_decode($response,true);
        return $result;
    }
    public function materialpost2($url,$data){
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_HEADER, false);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch,CURLOPT_BINARYTRANSFER,true);
        curl_setopt($ch, CURLOPT_POSTFIELDS,http_build_query($data));
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_exec($ch);
        curl_close($ch);
    }
    public function materialget($url){
        //初始�?
        $ch = curl_init();

        //设置选项，包括URL
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        //执行并获取HTML文档内容
        $output = curl_exec($ch);

        //释放curl句柄
        curl_close($ch);
        //打印获得的数�?
        return json_decode($output,true);
    }
}